import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hive/hive.dart';
import 'package:sleep_manager/data/family_info.dart';
import 'package:sleep_manager/ui/widget/custom_app_bar.dart';
import 'package:sleep_manager/utils/navigation_utils.dart';

/// 我的家人
class MyFamilyPage extends StatefulWidget {

  const MyFamilyPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MyFamilyPageState();
  }

}

class _MyFamilyPageState extends State<MyFamilyPage> {

  final NavigationUtils navigationUtils = NavigationUtils();

  // 列表的数据源
  List<FamilyInfo> _familyList = [];

  @override
  void initState() {
    super.initState();
    _fetchDataFromHive();
  }

  // 查询数据库列表
  Future<void> _fetchDataFromHive() async {
    final familyInfoBox = Hive.box<FamilyInfo>('familyInfoBox');
    setState(() {
      _familyList = familyInfoBox.values.toList();
    });
  }

  // 自定义item
  Widget _buildListViewItem(BuildContext context, int index) {

    final familyInfo = _familyList[index];

    return GestureDetector(
      onTap: () => {},
      child: Container(
        margin: const EdgeInsets.fromLTRB(16, 9, 16, 6),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 26),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 8,
                  spreadRadius: 2,
                  offset: const Offset(2, 2))
            ]),
        child: Column(
          children: [
            Row(
              children: [
                const Icon(Icons.icecream_rounded, size: 30),
                const SizedBox(width: 10),
                Text(
                  familyInfo.userName,
                  style: const TextStyle(
                    color: Colors.black,
                    fontSize: 15,
                    fontWeight: FontWeight.bold
                  ),
                ),
                Expanded(child: Container()),
                GestureDetector(
                  onTap: () => delete(index),
                  child: SvgPicture.asset('assets/images/delete.svg', width: 12, height: 12),
                ),
                const SizedBox(width: 20),
                GestureDetector(
                  onTap: () => {},
                  child: SvgPicture.asset('assets/images/edit.svg', width: 12, height: 12),
                )
              ],
            ),
            const SizedBox(height: 10),
            Row(
              children: [
                const SizedBox(width: 39),
                Expanded(
                  flex: 1,
                  child: Text(
                    '性别：${familyInfo.gender}',
                    style: const TextStyle(
                      color: Colors.black,
                      fontSize: 10
                    ),
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Text(
                    '年龄：${familyInfo.age}',
                    style: const TextStyle(
                        color: Colors.black,
                        fontSize: 10
                    ),
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Text(
                    '体重：${familyInfo.weight}kg',
                    style: const TextStyle(
                        color: Colors.black,
                        fontSize: 10
                    ),
                  ),
                )
              ],
            ),
            const SizedBox(height: 6),
            Row(
              children: [
                const SizedBox(width: 39),
                const Expanded(
                  flex: 1,
                  child: Text(
                    '证件类别：身份证',
                    style: TextStyle(
                        color: Colors.black,
                        fontSize: 10
                    ),
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: Text(
                    '证件号码：${familyInfo.idCard}',
                    style: const TextStyle(
                        color: Colors.black,
                        fontSize: 10
                    ),
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  // 添加家人
  Widget _addFamily() {
    return GestureDetector(
      onTap: () => { navigationUtils.navigateToPage(context, 'AddFamily', onRefresh: _refresh) },
      child: Container(
        alignment: Alignment.center,
        margin: const EdgeInsets.fromLTRB(16, 45, 16, 45),
        padding: const EdgeInsets.symmetric(vertical: 12),
        decoration: BoxDecoration(
            gradient: const LinearGradient(
              colors: [Color(0xFF80BFFF), Color(0xFF397AFB)],
            ),
            borderRadius: BorderRadius.circular(24)),
        child: const Text(
          '添加家人',
          style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold),
        ),
      ),
    );
  }

  // 刷新
  void _refresh() {
    _fetchDataFromHive();
  }

  // 删除
  void delete(int index) {
    final familyInfoBox = Hive.box<FamilyInfo>('familyInfoBox');

    final familyInfo = _familyList[index];

    for(var key in familyInfoBox.keys) {
      var info = familyInfoBox.get(key);
      if(familyInfo.idCard == info?.idCard) {
        familyInfoBox.delete(key);
      }
    }

    // 重新请求
    _fetchDataFromHive();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF7F7F7),
      appBar: const CustomAppBar(title: '我的家人', showBackButton: true),
      body: SingleChildScrollView(
        child:Column(
          children: [
            ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(), // 确保 ListView 不会滚动
              itemCount: _familyList.length,
              itemBuilder: (context, index) {
                return _buildListViewItem(context, index);
              },
            ),
            _addFamily(),
          ],
        ),
      ),
    );
  }
}
